(function( $, undefined ) {

$.widget("ui.ajajform_market_item_fields",$.ui.ajajform_widget, {
	options: {
		cssclass: "afw-market-item-fields",
		dictionaries: {},
		l10ns: [],
		htmltemplate:	'<table class="table">'+
						'<thead>'+
							'<tr>'+
								'<th>Параметр</th>'+
								'<th>Значение, язык:<span class="languages"></span></th>'+
								'<th>Тип данных</th>'+
								'<th>Видимость</th>'+
								'<th>Поиск</th>'+
								'<th></th>'+
							'</tr>'+
						'</thead>'+
						'<tbody>'+
						'</tbody>'+
						'<tfoot>'+
							'<tr class="split">'+
//								'<td colspan="6" class="af-buttons"><span>Добавить группу </span><div class="af-button af-button-add"></div></td>'+
							'</tr>'+
						'</tfoot>'+
						'</table>'
	},
	
	/**
	 *
	 */
	_create: function() {
		var t=this;
		this.element.addClass(this.options.cssclass);
		this.element.append(this.options.htmltemplate);
		this.renderGlobal();
		this.renderData();

		this.newGroupId=0;
		this.newFieldId=0;
	},

	/**
	 *
	 */
	renderGlobal: function() {
		var t=this;
		// Render language buttons
		for (var i=0;i<this.options.l10ns.length;i++) {
			$("<input type='button'/>").appendTo($(".languages",this.element)).attr("value",this.options.l10ns[i].name);
		}
		this.options.active_l10n_id=this.options.l10ns[0].id;
		$("tfoot .af-button-add").bind("click",function() {t.editGroupClicked(); });
	},

	/**
	 *
	 */
	renderData: function() {
		var t=this;
		var tbody=$("tbody",this.element).empty();
		var arr;

		// Render groups and items
		arr=this.options.dictionaries.field_groups[""];
		for (var i=0;i<arr.length;i++) {
			var g=arr[i];
			this.renderGroup(g);
		}
		arr=this.options.dictionaries.field_groups[this.options.category_id];
		for (var i=0;i<arr.length;i++) {
			var g=arr[i];
			this.renderGroup(g);
		}
		$("tbody tr:even",this.element).addClass("even");
		this.rendered_category_id=this.options.category_id;
		this.rendered_l10n_id=this.options.active_l10n_id;
	},
	/**
	 *
	 */
	renderGroup: function(g) {
		var t=this;
		var tbody=$("tbody",this.element);
		var cat={name:" - Для всех категорий - "};
		var arr=this.options.dictionaries.categories;
		for (var i=0;i<arr.length;i++) if (arr[i].id==g.category_id) cat=arr[i];

		var gtr=$('<tr class="split"><td colspan="5">'+cat.name+" / "+g.name+'</td><td class="af-buttons">'+/*<div class="af-button af-button-edit"></div>*/'<div class="af-button af-button-add"></div></td></tr>').appendTo(tbody);
//		$(".af-button-edit",gtr).bind("click",{},function(e) { t.editGroupClicked(g); });
		$(".af-button-add",gtr).bind("click",{},function(e) { t.editFieldClicked(g); });
		if (!g.children) g.children=[];
		for (var j=0;j<g.children.length;j++) {
			var f=g.children[j];
			var ftr=$('<tr>'+
						'<td class="name">'+f.name+'</td>'+
						'<td class="data data-'+f.id+'"></td>'+
						'<td class="datatype">'+f.datatype_name+'</td>'+
						'<td class="view_level">'+f.view_level_name+'</td>'+
						'<td class="search_level">'+f.search_level_name+'</td>'+
						'<td class="af-buttons"><div class="af-button af-button-edit"></div></td>'+
					'</tr>').appendTo(tbody);
			$(".af-button-edit",ftr).bind("click",{},function(e) { t.editFieldClicked(g,f)});
			var dt;
			var dts=this.options.dictionaries.datatypes;
			for (var i=0;i<dts.length;i++) if (dts[i].id==f.datatype_id) dt=dts[i];
			switch (dt.code) {
				case "integer":
				case "float":
				case "string":
				case "lstring":
				case "enum":
				case "lenum":
					var val=this.options.values[f.id];
					if (dts.has_l10n && val.l10ns) dts=val.l10ns[this.options.active_l10n_id];
					$('<input type="text"/>').appendTo($(".data",ftr)).val(val);
					break;
				case "enums":
				case "lenums":
					var val=this.options.values[f.id];
					$('<input type="text"/>').appendTo($(".data",ftr)).val(val?val.join(", "):"");
					break;
			}
		}
	},

	/**
	 *
	 */
	refreshCategory_id: function() {
		this.saveData(this.rendered_category_id);
		this.renderData();
	},

	/**
	 *
	 */
	editGroupClicked: function(g) {
		return;
		if (!g) g={l10ns:{}};
		var t=this;
		var div=$("<div class='jsdialog'></div>");
		var item=$('<div style="padding: 5px 0px;"><div style="float: left; width: 200px;">Привязана к категории</div><div style="float: left; width: 200px;"><input class="oncategory" type="checkbox"></div><div class="cl"></div></div>').appendTo(div);
		if (g.category_id) $("input",item).attr("checked",true);
		for (var i=0;i<this.options.l10ns.length;i++) {
			var l=this.options.l10ns[i];
			var item=$('<div style="padding: 5px 0px;"><div style="float: left; width: 200px;">'+l.name+'</div><div style="float: left; width: 200px;"><input class="name-'+l.id+'" type="text" style="width: 100%;"></div><div class="cl"></div></div>').appendTo(div);
			if (g.l10ns[l.id]) $("input",item).val(g.l10ns[l.id].name);
		}
		div.dialog({
			width:500,
			height:150+this.options.l10ns.length*36,
			title: "Редактирование группы",
			modal: true,
			buttons: {
				"Сохранить": function() {
					var options={
						l10ns:{},
						category_id:$("input.oncategory").attr("checked")?t.options.category_id:null
					};
					for (var i=0;i<t.options.l10ns.length;i++) {
						var l=t.options.l10ns[i];
						options.l10ns[l.id]={name:$("input.name-"+l.id,div).val()};
					}
					t.editGroup(g,options);
					$(".jsdialog").remove();
				}
			}
		});
	},

	/**
	 *
	 */
	editFieldClicked: function(g,f) {
		return;
		if (!f) f={l10ns:{},view_level_id:2};
		var t=this;
		var item;

		var div=$("<div class='jsdialog'></div>");
		function add_select(basediv,label,arr,name)
		{
			var item=$('<div style="padding: 5px 0px;"><div style="float: left; width: 200px;">'+label+'</div><div style="float: left; width: 200px;"><select name="'+name+'" style="width: 100%;"></select></div><div class="cl"></div></div>').appendTo(basediv);
			for (var i=0;i<arr.length;i++) {
				var dt=arr[i];
				$("select",item).append(new Option(dt.name,dt.id));
			}
			$("select",item).val(f[name]);
		}

		// Datatype
		if (f.datatype_id) {
			item=$('<div style="padding: 5px 0px;"><div style="float: left; width: 200px;">Тип данных:</div><div style="float: left; width: 200px;">'+f.datatype_name+'</div><div class="cl"></div></div>').appendTo(div);
		} else {
			add_select(div,"Тип данных",this.options.dictionaries.datatypes,"datatype_id");
		}

		// View level
		add_select(div,"Уровень просмотра",this.options.dictionaries.view_levels,"view_level_id");

		// Search level
		add_select(div,"Уровень поиска",this.options.dictionaries.search_levels,"search_level_id");

		// Name
		for (var i=0;i<this.options.l10ns.length;i++) {
			var l=this.options.l10ns[i];
			var item=$('<div style="padding: 5px 0px;"><div style="float: left; width: 200px;">'+l.name+'</div><div style="float: left; width: 200px;"><input class="name-'+l.id+'" style="width: 100%;"></div><div class="cl"></div></div>').appendTo(div);
			if (f.l10ns[l.id]) $("input",item).val(f.l10ns[l.id].name);
		}
		div.dialog({
			width:500,
			height:220+this.options.l10ns.length*36,
			title: "Редактирование поля",
			modal: true,
			buttons: {
				"Сохранить": function() {
					var options={
						l10ns:{},
						view_level_id:$("select[name='view_level_id']").val(),
						search_level_id:$("select[name='search_level_id']").val()
					};
					if (!f.id) options.datatype_id=$("select[name='datatype_id']").val();
					for (var i=0;i<t.options.l10ns.length;i++) {
						var l=t.options.l10ns[i];
						options.l10ns[l.id]={name:$("input.name-"+l.id,div).val()};
					}
					t.editField(g,f,options);
					$(".jsdialog").remove();
				}
			}
		});
	},

	/**
	 *
	 */
	decodeArr: function(arr,val) {
		for (var i=0;i<arr.length;i++) if (arr[i].id==val) return arr[i].name;
		return "";
	},

	/**
	 *
	 */
	editGroup: function(g,options) {
		this.saveData();
		if (!g.id) {
			g.id="new"+(++this.newGroupId);
			this.options.data.groups.push(g);
		}
		var fn;
		for (var k in options.l10ns) {
			if (!g.l10ns[k]) g.l10ns[k]={};
			if (!fn) fn=options.l10ns[k].name;
			g.l10ns[k].name=options.l10ns[k].name;
		}
		g.name=fn;
		this.renderData();
	},

	/**
	 *
	 */
	editField: function(g,f,options) {
		this.saveData();
		if (!f.id) {
			f.id="new"+(++this.newFieldId);
			g.fields.push(f);
		}
		var fn;
		for (var k in options.l10ns) {
			if (!f.l10ns[k]) f.l10ns[k]={};
			if (!fn) fn=options.l10ns[k].name;
			f.l10ns[k].name=options.l10ns[k].name;
		}
		for (var k in options) {
			if (k=="l10n") continue;
			f[k]=options[k];
		}
		f.datatype_name=this.decodeArr(this.options.data.datatypes,f.datatype_id);
		f.view_level_name=this.decodeArr(this.options.data.view_levels,f.view_level_id);
		f.search_level_name=this.decodeArr(this.options.data.search_levels,f.search_level_id);
		f.name=fn;
		this.renderData();
	},

	/**
	 *
	 */
	saveData: function(cat) {
		var cat_id=cat?cat.id:this.options.category_id;
		var t=this;
		var arr;

		// Render groups and items
		arr=this.options.dictionaries.field_groups[""];
		for (var i=0;i<arr.length;i++) {
			var g=arr[i];
			this.saveGroup(g);
		}
		arr=this.options.dictionaries.field_groups[cat_id];
		for (var i=0;i<arr.length;i++) {
			var g=arr[i];
			this.saveGroup(g);
		}
	},

	/**
	 *
	 */
	saveGroup: function(g) {
		var t=this;
		var arr=this.options.dictionaries.categories;
		if (!g.children) g.children=[];
		for (var j=0;j<g.children.length;j++) {
			var f=g.children[j];
			console.log(f);
			var td=$("td.data-"+f.id,this.element);
			var dt;
			var dts=this.options.dictionaries.datatypes;
			for (var i=0;i<dts.length;i++) if (dts[i].id==f.datatype_id) dt=dts[i];
			switch (dt.code) {
				case "integer":
				case "float":
				case "string":
				case "lstring":
				case "enum":
				case "lenum":
					var val=$("input",td).val();
					if (!this.options.values[f.id]) {
						if (dts.has_l10n) this.options.values[f.id]={l10ns:{}}; else this.options.values[f.id]="";
					}
					if (dts.has_l10n) {
						this.options.values[f.id].l10ns[this.rendered_l10n_id]=val;
					} else {
						this.options.values[f.id]=val;
					}
					break;
				case "enums":
				case "lenums":
					var val=$("input",td).val();
					this.options.values[f.id]=val.replace(/^\s+/).replace(/\s+$/).split(/\s*,\s*/);
					break;
			}
		}
	},

	/**
	 *
	 */
	postvalue: function(r) {
		this.saveData();
		r[this.options.name]=JSON.stringify(this.options.values);
	}
});

})( jQuery );

